﻿using System;
using Hsi.Utility.Identity;

namespace IdentityAtRest.Utility.Identity
{
    public class ExpressionAuthPolicyFactory : IExpressionAuthPolicyFactory
    {
        private readonly IExpressionEvaluator _expressionEval;

        public ExpressionAuthPolicyFactory(IExpressionCompiler compiler):this(new ExpressionEvaluator(compiler,false))
        {
            
        }

        public ExpressionAuthPolicyFactory(IExpressionEvaluator evaluator)
        {
            _expressionEval = evaluator;
            DefaultPolicyExpression = "false";
        }

        public string DefaultPolicyExpression { get; set; }

        public IAuthorizationPolicy CreatePolicy(string permission,string policyExpressionString)
        {
            //If no policy expression
            if (String.IsNullOrEmpty(policyExpressionString))
                policyExpressionString = DefaultPolicyExpression;

            IExpression<bool> policyExpression = _expressionEval.CompileExpression<bool>(policyExpressionString);

            return new ExpressionAuthPolicy(permission, policyExpression,policyExpressionString);
        }
    }
}